<template>
  <div style="height: 100%;">
    <div class="top-header">
      <!--<div class="menu" @click="showMenu = true"><img src="../../../../assets/img/icon-menu.png" alt="" width="100%"></div>-->
      <div class="time">
        <span class="year">{{ time }}</span>
        <span class="week-tag">第{{ nowWeek }}周</span>
      </div>
      <div class="home">
        <router-link to="/my/index">
          <img src="../../../../assets/img/icon-home.png" alt="" width="100%">
        </router-link>
      </div>
    </div>
    <div class="top-week">
      <div class="week-item" v-for="(item, index) in weeks" :key="index">{{ item }}</div>
    </div>
    <div class="swipe">
      <van-swipe :show-indicators="false" :loop="false" :initial-swipe="swipeIndex" @change="swipeChange" ref="swipe">
        <van-swipe-item v-for="(item, index) in dateArr" :key="index">
          <div class="top-date">
            <div :class="{'date-item': true, 'today': e.isToday}" v-for="(e, i) in item" :key="i">
              <div class="circle">
                <p class="date">{{ e.day }}</p>
                <p class="lunar">{{ e.dayCn }}</p>
              </div>
            </div>
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="calendar">
      <div class="course">
        <div v-for="(item, index) in courseList" :key="index" :class="{'row': true, 'first': index === 0}">
          <div class="col first">
            <div class="scale">{{ hours[index].name }}</div>
          </div>
          <div class="col" v-for="i in 7" :key="i">
            <div class="scale" @click="clickItem" :data-day="i - 1" :data-time="index" :style="{zIndex: (item && item[i - 1]) ? '2' : '1'}">
              <template v-if="item && item[i - 1]">
                <span
                  class="col-item"
                  v-for="(e, idx) in item[i - 1]"
                  :key="idx"
                  @click.stop="clickSpan(e)"
                  :style="{top: e.top + 'px', height: e.height + 'px', background: e.leave ? '#E5E3E6' : (e.type === 1 ? '#F7D5DA' : '#CFDFF3')}">
                  <p class="name">{{ e.name }}</p>
                  <p class="clazz-time">{{ e.leave ? '请假' : (e.start + '-' + e.end) }}</p>
                </span>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课程查看弹出层 -->
    <van-dialog
      class="close-dialog"
      v-model="showCourse"
      :show-confirm-button="false">
      <van-field v-model="course.kcname" label="课程名称" disabled/>
      <van-field v-model="course.name" label="学生姓名" disabled/>
      <van-field v-model="course.time" label="上课时间" disabled @click="showTime = true"/>
      <van-field type="textarea" autosize v-model="course.skplace" label="上课地点" disabled @click="showAddress = true"/>
      <van-field type="textarea" autosize v-model="dqplace" label="详细地址"/>
      <div class="bottom-btns">
        <van-divider/>
        <div class="bottom-btn">
          <router-link :to="`/editCourse?id=${course.id}`">
            <button>排课</button>
          </router-link>
        </div>
        <van-divider/>
        <div class="bottom-btn">
          <router-link :to="`/courseAssess?name=${user.name}&id=${course.id}&kcname=${course.kcname}`">
            <button>评价</button>
          </router-link>
        </div>
        <van-divider/>
        <div class="bottom-btn">
          <button @click="changeCourse">临时调课</button>
        </div>
      </div>
      <div class="close" slot="title" @click="closeDialog"><img src="../../../../assets/img/icon-close.png" alt=""></div>
    </van-dialog>

    <!-- 上课时间 -->
    <van-popup
      v-model="showTime"
      position="bottom">
      <van-datetime-picker
        type="datetime"
        :title="timeTitle"
        :min-date="minDate"
        @confirm="onSelectTime"
        @cancel="initUpdateTime"/>
    </van-popup>

    <!-- 所在地区 -->
    <van-popup
      v-model="showAddress"
      position="bottom">
      <van-area
        :area-list="areaList"
        title="选择上课区域"
        @cancel="showAddress = false"
        @confirm="onSelectAddress"/>
    </van-popup>
  </div>
</template>

<script>
import {getWeekDate, datetimeFormat, getWeekIndexInYear} from '@/utils'
import solarLunar from 'solarlunar'
import api from '@/api'
import area from '@/assets/js/area'
export default {
  name: 'index2',
  data () {
    return {
      courseList: new Array(19),

      time: '',
      weeks: ['一', '二', '三', '四', '五', '六', '日'],
      hours: [
        {name: '6', value: 6},
        {name: '7', value: 7},
        {name: '8', value: 8},
        {name: '9', value: 9},
        {name: '10', value: 10},
        {name: '11', value: 11},
        {name: '12', value: 12},
        {name: '13', value: 13},
        {name: '14', value: 14},
        {name: '15', value: 15},
        {name: '16', value: 16},
        {name: '17', value: 17},
        {name: '18', value: 18},
        {name: '19', value: 19},
        {name: '20', value: 20},
        {name: '21', value: 21},
        {name: '22', value: 22},
        {name: '23', value: 23},
        {name: '24', value: 24}
      ],
      dates: [],
      dateArr: [],
      showCourse: false,
      course: {
        id: '',
        profile_id: '',
        kcname: '',
        name: '',
        skplace: '',
        time: '',
        dqplace: ''
      },
      swipeIndex: 1,
      target: null,
      cover: null,
      nowWeek: '',
      showTime: false,
      showAddress: false,
      updateTime: [],
      saveTime: [],
      areaList: area,
      timeTitle: '请选择上课时间',
      minDate: new Date(),
      updatePlace: '',
      dqplace: '',
      user: sessionStorage.getItem('user') ? JSON.parse(sessionStorage.getItem('user')) : {}
    }
  },
  methods: {
    getCourse (times) {
      let params = {
        teacher_id: JSON.parse(sessionStorage.getItem('user')).id
      }
      if (times) {
        params.ktime = times[0]
        params.jtime = times[1]
      }
      api.teachetCourseIndex({
        params,
        callback: res => {
          if (res.data.error_code === 0) {
            let db = []
            res.data.data.forEach(item => {
              let start = datetimeFormat(new Date(Number(item.sktime) * 1000))
              let end = datetimeFormat(new Date(Number(item.xktime) * 1000))
              db.push({
                name: item.kech,
                date: start.split(' ')[0],
                start: start.split(' ')[1],
                end: end.split(' ')[1],
                type: item.kech === '集体' ? 2 : 1,
                id: item.id,
                leave: item.kech !== '集体' && item.status === 1
              })
            })
            this.dbHandle(db)
          } else {
            this.dbHandle([])
          }
        }
      })
    },
    swipeChange (index) {
      this.dates = this.dateArr[index]
      this.nowWeek = getWeekIndexInYear(new Date(this.dates[0].dateStr))
      this.time = `${this.dates[0].dateStr.split('/')[0]}年${this.dates[0].dateStr.split('/')[1]}月`
      setTimeout(() => {
        if (index === 0) {
          // unshift
          this.dateArr.unshift(this.dateArrHandle(getWeekDate(new Date(this.dates[0].dateStr).valueOf() - (24 * 3600 * 1000))))
          this.swipeIndex = 1
        } else if (index === this.dateArr.length - 1) {
          // push
          this.dateArr.push(this.dateArrHandle(getWeekDate(new Date(this.dates[6].dateStr).valueOf() + (24 * 3600 * 1000))))
          this.swipeIndex = index
        }
      }, 500)
      let times = [new Date(this.dates[0].dateStr) / 1000, new Date(this.dates[this.dates.length - 1].dateStr + ' 23:59:59') / 1000]
      this.getCourse(times)
    },

    toSelectStudent () {
      window.sessionStorage.setItem('addForm', JSON.stringify(this.addForm))
      this.$router.push('/select/student/list')
    },

    dateArrHandle (arr) {
      return arr.map((item, index) => {
        let lunar = solarLunar.solar2lunar(item.split('/')[0], item.split('/')[1], item.split('/')[2])
        let dayCn = lunar.dayCn
        if (lunar.isTerm) {
          dayCn = lunar.term
        }
        if (lunar.lDay === 1) {
          dayCn = lunar.monthCn
        }
        return {
          dateStr: item,
          week: this.weeks[index],
          day: item.split('/')[2],
          dayCn,
          isToday: lunar.isToday
        }
      })
    },

    // 点击事件
    clickSpan (clazz) {
      api.teacherCourseDetail({
        params: {id: clazz.id},
        callback: res => {
          if (res.data.error_code === 0) {
            Object.keys(this.course).forEach(key => {
              this.course[key] = res.data.data[key]
            })
            let start = datetimeFormat(new Date(Number(res.data.data.sktime) * 1000))
            let end = datetimeFormat(new Date(Number(res.data.data.xktime) * 1000))
            this.course.time = start + '-' + end.split(' ')[1]
            this.dqplace = this.course.dqplace
            this.showCourse = true
          }
        }
      })
    },
    clickItem (e) {
      let day = this.dates[e.target.dataset.day].dateStr
      let startH = this.hours[e.target.dataset.time].value
      let endH = this.hours[e.target.dataset.time].value + 1
      if (this.target) {
        this.target.removeChild(this.cover)
      }
      let dom = document.createElement('div')
      let _self = this
      dom.className = 'cover-item'
      dom.onclick = function (ev) {
        // this.$emit('toAddCourse')
        let url = `/editCourse?day=${day}&start=${startH}&end=${endH}`
        _self.$router.push(url)
        ev.stopPropagation()
      }
      dom.innerText = '+'
      e.target.appendChild(dom)
      this.target = e.target
      this.cover = dom
    },

    dbHandle (db) {
      let arr = new Array(19)
      db.forEach(item => {
        let week = new Date(item.date).getDay() - 1
        if (week < 0) {
          week = 6
        }
        let hour = Number(item.start.split(':')[0])
        let min = Number(item.start.split(':')[1])

        let endH = Number(item.end.split(':')[0])
        let endM = Number(item.end.split(':')[1])
        let index = hour - 6
        if (!arr[index]) {
          arr[index] = new Array(7)
        }

        item.top = min * 2
        item.height = ((endH - hour) * 60 + (endM - min)) * 2
        if (!arr[index][week]) {
          arr[index][week] = []
        }
        arr[index][week].push(item)
      })
      this.courseList = arr
    },

    onSelectTime (date) {
      if (this.updateTime.length === 0) {
        this.updateTime.push(date.valueOf() / 1000)
        this.timeTitle = '请选择下课时间'
        this.minDate = date
        this.showTime = false
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true,
          duration: 1000,
          loadingType: 'spinner',
          onClose: () => {
            this.showTime = true
          }
        })
      } else if (this.updateTime.length === 1) {
        this.updateTime.push(date.valueOf() / 1000)
        let start = datetimeFormat(new Date(this.updateTime[0] * 1000))
        let end = datetimeFormat(new Date(this.updateTime[1] * 1000))
        this.course.time = start + '-' + end.split(' ')[1]
        this.saveTime = this.updateTime
        this.timeTitle = '请选择上课时间'
        this.updateTime = []
        this.showTime = false
      }
    },
    initUpdateTime () {
      this.updateTime = []
      this.showTime = false
    },
    onSelectAddress (arr) {
      let code = []
      let city = []
      arr.forEach(item => {
        code.push(item.code)
        city.push(item.name)
      })
      this.course.skplace = city.join(' ')
      this.updatePlace = city.join(' ')
      this.showAddress = false
    },
    changeCourse () {
      if (this.saveTime.length === 0 && this.updatePlace === '' && this.dqplace === this.course.dqplace) {
        this.$toast('请修改上课时段或上课地点')
        return
      }
      let params = {
        id: this.course.id
      }
      if (this.saveTime.length !== 0) {
        // let date = this.course.time.split(' ')[0].replace('-', '/')
        params.sktime = this.saveTime[0]
        params.xktime = this.saveTime[1]
      }
      if (this.updatePlace !== '') {
        params.skplace = this.updatePlace
      }
      if (this.dqplace !== this.course.dqplace) {
        params.dqplace = this.dqplace
      }
      api.teacherChangeCourse({
        params,
        callback: res => {
          if (res.data.error_code === 0) {
            this.initUpdateTime()
            this.$toast({
              message: '调课成功',
              duration: 1000,
              onClose: () => {
                let times = [new Date(this.dates[0].dateStr) / 1000, new Date(this.dates[this.dates.length - 1].dateStr + ' 23:59:59') / 1000]
                this.getCourse(times)
              }
            })
          }
        }
      })
    },

    closeDialog () {
      this.showCourse = false
      this.initUpdateTime()
    }
  },
  created () {
    // this.getCourse()
    const date = new Date()
    this.time = `${date.getFullYear()}年${date.getMonth() + 1}月`

    this.dates = this.dateArrHandle(getWeekDate())
    this.nowWeek = getWeekIndexInYear(new Date(this.dates[0].dateStr))
    this.dateArr = [
      this.dateArrHandle(getWeekDate(new Date(this.dates[0].dateStr).valueOf() - (24 * 3600 * 1000))),
      this.dateArrHandle(getWeekDate()),
      this.dateArrHandle(getWeekDate(new Date(this.dates[6].dateStr).valueOf() + (24 * 3600 * 1000)))
    ]
    let times = [new Date(this.dates[0].dateStr) / 1000, new Date(this.dates[this.dates.length - 1].dateStr + ' 23:59:59') / 1000]
    this.getCourse(times)
  }
}
</script>

<style scoped>
  .top-header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    height: 30px;
  }
  .top-header .time{
    display: flex;
    align-items: center;
  }
  .top-header .time .year{
    font-size: 22px;
    font-family: PingFang SC;
    font-weight: bold;
    line-height: 30px;
    color: rgba(30,30,30,1);
    margin-right: 16px;
  }
  .top-header .time .week-tag{
    display: inline-block;
    padding: 2px 12px;
    background-color: #E8E8E8;
    border-radius: 20px;
    font-size: 14px;
    font-family: "PingFang SC";
  }
  .top-header .home{
    width: 22px;
    height: 22px;
  }

  .top-week{
    margin-bottom: 16px;
    height: 21px;
  }
  .top-date, .top-week{
    display: flex;
    padding: 0 8px 0 20px;
    background-color: #fff;
  }
  .top-date .date-item, .top-week .week-item{
    flex: 1;
    text-align: center;
    font-weight: bold;
    color: #2D2D2D;
    font-family: PingFangBlod;
  }
  .swipe{
    height: 42px;
    margin-bottom: 10px;
  }
  .date-item .lunar{
    color: #999999;
    font-size: 10px;
  }
  .date-item .circle{
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .date-item.today .circle{
    border: 1px solid #C7DDE5;
  }
  .calendar{
    height: calc(100% - 139px);
    overflow-y: auto;
  }
  .course{
    padding: 10px 8px 0 0;
    background-color: #F2F2F2;
  }
  .course .row{
    display: flex;
    height: 60px;
  }
  .course .row .col{
    flex-grow: 1;
    flex-shrink: 1;
    position: relative;
  }
  .course .row .first{
    width: 20px;
    flex-grow: 0;
    flex-shrink: 0;
    font-size: 24px;
    font-family: PingFangBlod;
    text-align: center;
  }
  .row .col .scale{
    box-sizing: border-box;
    border-right: 1px solid #DFDFDF;
    border-bottom: 1px solid #DFDFDF;
    transform: scale(0.5);
    position: absolute;
    top: -50%;
    bottom: -50%;
    left: -50%;
    right: -50%;
  }
  .row.first .col .scale{
    border-top: 1px solid #DFDFDF;
  }
  .col .scale .col-item{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: absolute;
    width: 100%;
    background-color: #CFDFF3;
    border: 1px solid #F2F2F2;
    box-sizing: border-box;
    word-wrap:break-word;
    word-break:break-all;
  }
  .col-item .name{
    font-size: 24px;
    font-family: PingFangBlod;
    line-height: 36px;
  }
  .col-item .clazz-time{
    font-size: 14px;
  }
  .van-divider{
    margin: 0;
  }

  .grid-box{
    flex-shrink: 1;
    flex-grow: 1;
  }
  .van-grid{
    height: 100%;
  }
</style>
